package cn.edu.pzhu.javaweb.controller;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import cn.edu.pzhu.javaweb.pojo.Result;
import cn.edu.pzhu.javaweb.service.UserService;
import cn.edu.pzhu.javaweb.service.imp.UserServiceImp;

/**
 * 注销账户控制器
 */
@WebServlet("/destroy")
public class DestroyServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private UserService userService = new UserServiceImp();

    /**
     * 处理 GET 请求，转发到注销确认页面
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        request.setCharacterEncoding("UTF-8");

        HttpSession session = request.getSession();
        String username = (String) session.getAttribute("username");

        // 检查用户是否登录
        if (username == null || username.isEmpty()) {
            response.getWriter().print("<script>alert('请先登录！');location.href='login.jsp';</script>");
            return;
        }

        // 转发到注销确认页面
        request.getRequestDispatcher("/WEB-INF/destroy.jsp").forward(request, response);
    }

    /**
     * 处理 POST 请求，验证密码并执行注销
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        request.setCharacterEncoding("UTF-8");

        HttpSession session = request.getSession();
        String username = (String) session.getAttribute("username");

        // 检查用户是否登录
        if (username == null || username.isEmpty()) {
            response.getWriter().print("<script>alert('请先登录！');location.href='login.jsp';</script>");
            return;
        }

        // 获取输入的密码
        String inputPassword = request.getParameter("pwd");
        
        // 数据验证
        if (inputPassword == null || inputPassword.isEmpty()) {
            response.getWriter().print("<script>alert('密码不能为空！');location.href='destroy';</script>");
            return;
        }
        
        // 使用Service层进行账户注销
        Result<String> result = userService.destroyAccount(username, inputPassword);
        
        if (result.getCode() == 0) {
            // 销毁 session
            session.invalidate();
            
            // 提示并跳转到登录页面
            response.getWriter().print("<script>alert('账户已成功注销！');location.href='login.jsp';</script>");
        } else {
            // 提示失败信息
            response.getWriter().print("<script>alert('" + result.getMessage() + "');location.href='destroy';</script>");
        }
    }
}